package com.wyd.jwpkglxt_ssm.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wyd.jwpkglxt_ssm.util.JWTUtil;
import com.wyd.jwpkglxt_ssm.util.ResultCode;
import com.wyd.jwpkglxt_ssm.util.ResultUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("token")
public class TokenController {

    //@GetMapping("get-login-token")
    //public ResultUtil getLoginToken(HttpServletRequest request){
    //    HttpSession session = request.getSession();
    //    Map<String, String> map = new HashMap<>();
    //    map.put("data",String.valueOf(new Date().getTime()));
    //    String token = JWTUtil.getToken(map);
    //
    //    session.setAttribute("token_login",token);
    //
    //    return ResultUtil.ok().data("token",token);
    //
    //}

    @PostMapping("login")
    public ResultUtil loginByToken(@RequestParam(required = false) String token,HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println(token);
        if(!"".equals(token)&&token!=null){
            try{
                DecodedJWT verify = JWTUtil.verify(token);
                session.setAttribute("token", token);
                return ResultUtil.ok().data("userId",verify.getClaim("userId").asString()).data("username",verify.getClaim("username").asString())
                        .data("realName",verify.getClaim("realName").asString()).data("roleId",verify.getClaim("roleId").asString());
            }catch (SignatureVerificationException e){
                e.printStackTrace();
                //无效签名
            }catch (TokenExpiredException e){
                e.printStackTrace();
                //token过期
            }catch (AlgorithmMismatchException e){
                e.printStackTrace();
                //token算法不一致!
            }catch (Exception e){
                e.printStackTrace();
                //token无效
            }


        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }

    @GetMapping("get-token")
    public ResultUtil getToken(HttpServletRequest request){
        HttpSession session = request.getSession();
        return ResultUtil.ok().data("token",session.getAttribute("token").toString());
    }
}
